package com.jmda.platform.commom.util;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {
	// 获得指定路径下所有后缀为xml的文件名
	public static List<String> getXmlFileList(String path) {
		List<String> list = new ArrayList<String>();
		File f = new File(path);
		if (f.exists()) {
			for (int i = 0; i < f.list().length; i++) {
				if (f.list()[i].endsWith(".xml"))
					list.add(f.list()[i]);
			}
		}
		return list;
	}

	// 使用utf-8编码将指定的xml文件转换为指定的对象
	public static <T> T coverXmlToBean(Class<T> type, String xmlFileAbsolutePath) {
		try {
			File xmlFile = new File(xmlFileAbsolutePath);
			if (xmlFile.exists()) {
				String fileContent = readAll(xmlFileAbsolutePath);
				XStream xstream = new XStream(new DomDriver("utf-8"));
				xstream.processAnnotations(type);
				return (T) xstream.fromXML(fileContent);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	public static void write(String srcFileName, String fileContent, String encodeing) throws IOException {
		BufferedWriter bf = null;
		try {
			bf = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(srcFileName), encodeing));
			String[] ss = fileContent.split("__eol__");
			for (int i = 0; i < ss.length; i++) {
				bf.write(ss[i]);
				if (i != ss.length - 1) {
					bf.newLine();
				}
			}

			bf.flush();
		} finally {
			if (bf != null) {
				try {
					bf.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public static void write(String srcFileName, String fileContent) throws IOException {
		write(srcFileName, fileContent, "UTF8");
	}

	// 删除指定文件
	public static void removeFile(String fileAbsolutePath) {
		File xmlFile = new File(fileAbsolutePath);
		if (xmlFile.exists()) {
			xmlFile.delete();
		}
	}

	// 使用UTF-8编码读取指定文件的内容
	public static String readAll(String fileName) throws IOException {
		return readAll(fileName, "UTF-8");
	}

	// 使用指定编码读取指定文件的内容
	public static String readAll(String fileName, String encodeing) throws IOException {
		FileInputStream in = null;
		try {
			in = new FileInputStream(fileName);
			String res;
			int len = in.available();
			if (len > 0) {
				byte[] buf = new byte[len];
				in.read(buf, 0, len);
				res = (new String(buf, encodeing));
			} else {
				res = null;
			}
			return res;
		} finally {
			try {
				in.close();
				in = null;
			} catch (Exception e) {
			}
		}
	}
}
